package org.example.pack;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * <p> Netty 客户端 Handler </p>
 *
 * @author Chris
 * @since 2024/3/25 17:34
 */
public class TimeClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(TimeClientHandler.class);
    private int counter;
    private final byte[] req;

    public TimeClientHandler() {
        this.req = ("QUERY TIME ORDER" + System.lineSeparator()).getBytes();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ByteBuf message;
        for (int i = 0; i < 100; i++) {
            message = Unpooled.buffer(req.length);
            message.writeBytes(this.req);
            ctx.writeAndFlush(message);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        final String body = (String) msg;
        log.info("Now is : {}; the counter is : {}", body, ++this.counter);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("Unexpected exception from downstream : ", cause);
        ctx.close();
    }

}